package com.study.order.interceptor;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
 * @author caoqianhuan
 * @date 2022/9/7
 * @Description:
 */
@Component
public class AuthenticationInterceptor implements HandlerInterceptor {
    @Value("${oss.url}")
    private String ossUrl;
    private static final String IS_LOGIN = "isLogin";
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        System.out.println("身份验证拦截器执行");
        System.out.println(request.getRequestURL());

        HttpSession session = request.getSession();
        String auth = request.getParameter("auth");
        String ticket = request.getParameter("ticket");
        System.out.println(ticket);
        if (auth != null && auth.equals("true")) {
            session.setAttribute(IS_LOGIN, true);
        }
        Boolean isLogin = (Boolean) session.getAttribute(IS_LOGIN);
        if (isLogin == null || !isLogin) {
            //Map<String, Object> params = new HashMap<>();
            //params.put("url", request.getRequestURL().toString());
            ////当值为空时fastjson默认不将其序列化到JSON字符串之中
            //params.put("ticket", ticket);
            //response.sendRedirect(ossUrl + ticket);
            //System.out.println(JSON.toJSONString(params));
            //不能直接发http请求 这样不仅请求端会抛异常，被请求端也不能重定向
            //String resp = HttpUtil.createPost(ossUrl).form("url", request.getRequestURL().toString())
            //        .form("ticket", ticket).execute().body();
            //System.out.println(resp + "aaa");
            //boolean auth = JSON.parseObject(resp).getBoolean("isLogin");
            StringBuilder builder = new StringBuilder();
            //String param = JSON.toJSONString(params);
            //System.out.println(param);
            builder.append(ossUrl).append("?url=").append(request.getRequestURL()).append("&ticket=").append(ticket);
            System.out.println("开始重定向");
            response.sendRedirect(builder.toString());

        }
        return HandlerInterceptor.super.preHandle(request, response, handler);
    }
}
